// pages/familyFeast/settlement.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "家宴", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    addressList: [],
    address: '默认地址',
    name: '',
    phone: '',
    notes: '',

    openid: '',
    shareTitle: '',
    shareImg: '',
    bm_time: '', //预约的日期
    yy_time: '', //预约时段 1：午餐  2：晚餐
    yhMoney: 0, //优惠明细--优惠金额
    goodsAmount: 0, //优惠明细--商品合计
    yhAmount: 0, //优惠明细--优惠
    dbFee: 0, //打包费
    psFee: 0, //配送费
    qsMoney: 0,
    carFoodList: [],
    regInfo: [], //注册信息
    sdTime: '', //预计送达时间
    zjMoney: 0,
    hjMoney: 0,
    people_number: 0
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  addressChange(e) {
    let that = this;
    that.setData({
      address: that.data.addressList[e.detail.value].name,
    })
  },
  // 姓名
  nameIpt(e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 电话
  phoneIpt(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  notes: function (e) {
    var value = e.detail.value;
    this.setData({
      notes: value //当前字数
    })
  },
  order() {
    let that = this;
    let name = that.data.name;
    let phone = that.data.phone;
    let address = that.data.address;
    if (address == '' || address == '默认地址') {
      app.showTip("请选择配送地址");
      return;
    } else if (name == "") {
      app.showTip("请填写姓名");
      return;
    } else if (phone == "") {
      app.showTip("请填写电话");
      return;
    } else if (phone.length != 11) {
      app.showTip("请填写正确的电话");
      return;
    } else if ((that.data.yhAmount - that.data.dbFee) < that.data.qsMoney) {
      app.showTip("抱歉,您订购的菜品暂未达到起送价格哦");
      return;
    } else if (that.data.carFoodList.length <= 0) {
      app.showTip("抱歉,未获取到您选择的商品信息哦");
      return;
    }

    //将数据提交至后台
    wx.showLoading({
      title: '订餐中,请稍候...'
    });

    wx.request({
      url: that.data.baseUrl + 'addFamilyFeastOrder.php',
      method: 'POST',
      data: {
        openid: that.data.openid,
        bm_time: that.data.bm_time,
        yy_time: that.data.yy_time,
        carFoodList: JSON.stringify(that.data.carFoodList),
        ps_address: that.data.address,
        name: that.data.name,
        tel: that.data.phone,
        sd_time: that.data.sdTime,
        db_money: that.data.dbFee,
        ps_moeny: that.data.psFee,
        yh_money: that.data.yhMoney,
        payAmount: that.data.hjMoney,
        qsMoney: that.data.qsMoney,
        remark: that.data.notes,
        people_number:that.data.people_number
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        app.showTip(res.data.msg);
        if (res.data.status == 1) {
          //后台请求成功
          setTimeout(function () {
            wx.redirectTo({
              url: '/pages/familyFeast/orderDetail?id=' + res.data.id
            });
          }, 1500)
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
        return;
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;

    //获取页面参数
    var bm_time = options.bm_time;
    var yy_time = options.yy_time;
    var people_number = options.people_number;
    //bm_time = '2024-06-28';
    //yy_time=1;

    //参数判断
    if (bm_time == '' || bm_time == undefined) {
      app.showTip('抱歉,未获取到订餐日期哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1400);
      return;
    }

    if (yy_time != 1 && yy_time != 2) {
      app.showTip('抱歉,未获取到订餐时段哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1400);
      return;
    }

    
    //判断用餐人数
    if (parseInt(people_number)==0) { 
      app.showTip('抱歉,未获取到用餐人数信息哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1400);
      return;
    }

    //保存数据
    that.setData({
      bm_time: bm_time,
      yy_time: yy_time,
      people_number:people_number
    });

    //读取缓存中的订单信息 浮点数只能减不能加
    var carFoodList = wx.getStorageSync('carFoodList');
    var dbFee = that.gshNum(wx.getStorageSync('dbFee'));
    var psFee = that.gshNum(wx.getStorageSync('psFee'));
    var qsMoney = that.gshNum(wx.getStorageSync('qsMoney'));
    var goodsAmount = that.gshNum(wx.getStorageSync('goodsAmount'));
    var yhMoney = that.gshNum(wx.getStorageSync('yhMoney'));
    var yhAmount = that.gshNum(wx.getStorageSync('yhAmount'));
    var zjMoney = yhAmount - dbFee;
    var hjMoney = parseFloat(yhAmount);

    //判断购物车中的是否存在商品
    if (carFoodList.length <= 0) {
      app.showTip('抱歉,未获取到购物车商品信息哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1400);
      return;
    }

    //保存信息
    that.setData({
      carFoodList: carFoodList,
      dbFee: dbFee,
      psFee: psFee,
      qsMoney: qsMoney,
      goodsAmount: goodsAmount,
      yhMoney: yhMoney,
      yhAmount: yhAmount,
      zjMoney: zjMoney,
      hjMoney: hjMoney
    });

    //清空缓存
    wx.setStorageSync('carFoodList', []);
    wx.setStorageSync('dbFee', 0);
    wx.setStorageSync('psFee', 0);
    wx.setStorageSync('qsMoney', 0);
    wx.setStorageSync('goodsAmount', 0);
    wx.setStorageSync('yhMoney', 0);
    wx.setStorageSync('yhAmount', 0);

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getFamilyFeastSettlmentPageInfo(res.data.openid, bm_time, yy_time,people_number);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getFamilyFeastSettlmentPageInfo(openid, bm_time, yy_time,people_number);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getFamilyFeastSettlmentPageInfo(openid, bm_time, yy_time,people_number) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getFamilyFeastSettlmentPageInfo.php',
      method: 'POST',
      data: {
        openid: openid,
        bm_time: bm_time,
        yy_time: yy_time,
        people_number:people_number
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            addressList: res.data.myHouseList,
            regInfo: res.data.regInfo,
            sdTime: res.data.sdTime,
            name: res.data.regInfo.name,
            phone: res.data.regInfo.tel,
            address: res.data.myHouseList[0].name
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
        app.showTip('服务器繁忙,请稍候重试');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
        return;
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo_order.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //处理价格是整型还是浮点型数字
  gshNum(num) {
    if (!isNaN(num) && parseInt(num, 10) === parseFloat(num)) {
      //为整型
      return parseInt(num);
    } else {
      //为浮点型 保留两位小数
      return parseFloat(num).toFixed(2);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/familyFeast/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})